package ModelLayer;

import java.util.ArrayList;

/**
 * This is a container class designed to contain elements of Loan.
 * 
 * @author Sebastian K Munch
 * @version 08-11-2012
 */
public class LoanContainer
{
    private ArrayList<Loan> loans;
    private static LoanContainer instance;
    
    /**
     * Constructor for objects of class LoanContainer
     */
    private LoanContainer()
    {
        loans = new ArrayList<Loan>();
    }
    
    /**
     * This method returns the instance of this class, in acordance with singleton implamentation.
     */
    public static LoanContainer getInstance()
    {
        if(instance == null)
        {
            instance = new LoanContainer();
        }
        return instance;
    }
    
    /**
     * private support method, finds and returnds the index of a loan , based on id.
     */
    private int getLoanIndex(long id)
    {
        boolean found = false;
        int index = -1;
        int i = 0;
        while(!found && i < loans.size())
        {
            if(loans.get(i).getLoanID()==id)
            {
                index = i;
                found = true;
            }
            i++;
        }
        return index;
    }
    
    /**
     * This method associates a new element of Loan, to this class.
     * 
     * @param   loan    The new loan to be associated to this class. A Loan.
     */
    public void addLoan(Loan loan)
    {
        loans.add(loan);
    }
    
    /**
     * This method returns a Loan identified by id. If none is found null is returned
     * 
     * @param   id  The id of the Loan to be returned. A Long.
     */
    public Loan findLoan(long id)
    {
        return loans.get(getLoanIndex(id));
    }
    
    /**
     * The method removes a loan identified by the give id.
     * 
     * @param   id  The id of the loan to be removed. A long.
     */
    public boolean removeLoan(long id)
    {
        boolean s;
        int i = getLoanIndex(id);
        if(i == -1)
        {
            s = false;
        }
        else
        {
            s = true;
            loans.remove(i);
        }
        return s;
    }
    
    /**
     * This method returns a list of loans.
     * 
     * @return  A list of loans, an an ArrayList<Loan>
     */
    public ArrayList<Loan> listAllLoans()
    {
        return loans;
    }
}
